import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { config } from '../../../shared/smartadmin.config';
declare var $: any;
declare var Viewer: any;
@Component({
	selector: 'sa-user-info',
	templateUrl: './user-info.component.html',
	styleUrls:['./user-info.component.css'],
})
export class UserInfoComponent implements OnInit {
	tableData = []; //table数据
	totalCount:number = 0; //分页总条数
	curPage:number = 1; //分页当前页
	pageSize:number = 10; //内置的分页每页条数
	searchKey:string = ''; //搜索keyword
	startTime_table:string = '';
	endTime_table:string = '';
	selectedCompanyId:string = '';
	selectedCompanyName:string = '';
	carNumber:string = '';
	deviceId:string = '';
	jumpData:any; // 跳转页面接收到的数据
	formType:any="add"; // 新增
    initDateRange: any = {
        startTime:'',
        endTime:'',
	}// 时间组件需要渲染的值
	companyParentList:any = []
	constructor(private jsonApiService: JsonApiService, private router: Router,private activatedRoute: ActivatedRoute) {
		activatedRoute.queryParams.subscribe(queryParams => {
			this.curPage = queryParams.nowPage || 1;
			if(common.getCookie('jumpTo/langyun/calibration')){
                this.jumpData = JSON.parse(common.getCookie('jumpTo/langyun/calibration'));
                this.initDateRange.startTime = this.jumpData.startTime;
                this.initDateRange.endTime = this.jumpData.endTime;
            }
		});
	}
	validatorOptions = {
		excluded:[":disabled"],
		feedbackIcons: {
			valid: 'glyphicon glyphicon-ok',
			invalid: 'glyphicon glyphicon-remove',
			validating: 'glyphicon glyphicon-refresh'
		},
		fields: {
			carNumberFrom: {
				trigger:"change",
				validators: {
					notEmpty: {
						message: '请选择车牌号'
					}
				}
			},
			userName: {
				validators: {
					notEmpty: {
						message: '请输入用户姓名'
					}
				}
			},
			jobNum:{
				validators: {
					notEmpty: {
						message: '请输入工号'
					}
				}
			},
			phone:{
				validators: {
					notEmpty: {
						message: '请输入手机号'
					}
				}
			},
		}
	}
	ngOnInit() {
		let that = this;
		this.ngInitCompany();
	    if(common.getCookie('jumpTo/langyun/calibration')) {
            setTimeout(()=>{
                that.load();
            },100)
            common.clearCookie('jumpTo/langyun/calibration');
        }else{
            this.load();
        }
	}
	// 接收子组件传递过来的数据 
	getSelectTableTime(time){
		this.startTime_table = time.startTime;
		this.endTime_table = time.endTime;
	} 
	// 公司选中回调
    companySelected(data){
        this.selectedCompanyId = data.companyId;
        this.selectedCompanyName = data.companyName;
        this.deviceId = data.deviceId;
        this.carNumber = data.carNumber;
    }
	//表格搜索
	table_search() {
		this.curPage = 1
		this.searchKey = common.stringTrim(this.searchKey);
		this.load();
	}
	//刷新
	refresh(){
    	this.load();
    }
	//初始化加载list数据
	load() {
		let data = {
			pageSize:this.pageSize,
			nowPage:this.curPage,
			parameters:{
				companyId: this.selectedCompanyId,
				deviceId: this.deviceId,
				// carNumber: this.carNumber,
				startTime:this.startTime_table,
				endTime:this.endTime_table,
				searchKey:this.searchKey,
			}
		}
		let reqdata = 'gridPager='+JSON.stringify(data);
		this.jsonApiService.http("sanitationUser/sanitationUserList.html", reqdata).subscribe(data => {
			this.tableData = data.exhibitDatas;
			this.totalCount = data.recordCount;
		})
	}
	//分页回调
	paginate(e){
		this.curPage = e.page+1;
		this.pageSize = e.rows;
		this.load();
	}

	
	//父级公司树请求
	ngInitCompany() {
		this.jsonApiService.http("company/companytree.html",null).subscribe(data => {
			this.companyParentList = data;
		})
	}
	// 页面跳转
	// jumpCarList(row){
    //     let BaseURL = window.location.protocol + '//' + window.location.hostname + ':' + window.location.port;
    //     common.setCookie('jumpTo/system/car', JSON.stringify(row));
    //     window.open(BaseURL + '#/system/car');
	// }

	userObj:any = {
		id:"",
		installFactoryId:"",
		installFactoryName:"",
		deviceId:"",
		carNumber:"",
		userName:"",
		userPic:"",
		jobNum:"",
		phone:"",
		commandTime:''
	}
	// 添加用户界面打开
	showAddUserModal(modal){
		this.formType = 'add'
		let that = this;
		this.imageInfo ={
			"localImg":[],
			"imageList":[],
			"describe": '用户照片'
		}
		this.userObj = {
			id:"",
			installFactoryId:"",
			installFactoryName:"",
			deviceId:"",
			carNumber:"",
			userName:"",
			userPic:"",
			jobNum:"",
			phone:"",
			commandTime:''
		}
		var str=$("<span class='select2-selection__placeholder'>请选择</span>");
		$('#carNumberFrom').val("");
		$('#carSelect2').val("");
		$("#select2-carSelect2-container").empty();
		$("#select2-carSelect2-container").attr("title","");
		$("#select2-carSelect2-container").prepend(str);
		modal.show();
	}
	// 打开编辑用户
	showEditUserModal(row,modal){
		this.formType = 'update'
		this.userObj = JSON.parse(JSON.stringify(row))
		$("#select2-carSelect2-container").html('<span class="select2-selection__clear">×</span>' + row.carNumber)
		this.imageInfo ={
			"localImg":[],
			"imageList":[],
			"describe": '用户照片'
		}
		
		//显示图片
		let list = row.userPic?row.userPic.split(","):[]
		for(var i=0;i< list.length;i++){
			this.imageInfo.imageList.push(list[i]);
			
			let localImg;
			
			if(list[i].indexOf('http') == -1){
				if(list[i][0] == '/'){
					localImg = config.BaseURL + list[i].substr(1);
				}else{
					localImg = config.BaseURL + list[i];
				}
			}else{
				localImg = list[i];
			}
			this.imageInfo.localImg.push(localImg);
		}
		
		modal.show();
	}
	// 车辆组件数据回调
    optionSelected(data){
        this.userObj.carNumber = data.text;
        this.userObj.deviceId = data.id;
    }

	

	//新增或者编辑公司选中回调
	addCompanySelected1(data) {
		this.userObj.installFactoryId = data.companyId||'';
		this.userObj.installFactoryName = data.companyName;
	}
	// 添加用户界面关闭
	closeAddUserModal(modal){
		$("#userForm").data('bootstrapValidator').resetForm();
		modal.hide();
	}
	// 提交
	userInfoSubmit(modal){
		$('#userForm').bootstrapValidator('validate'); //开启验证
		let isValid = $('#userForm').data('bootstrapValidator').isValid();  //验证是否通过
		if(isValid){
			// console.log(this.userObj)
			this.userObj.userPic = this.imageInfo.imageList.join(",")
			if (this.formType == "add") {
				this.jsonApiService.http_obj("sanitationUser/add.html", this.userObj).subscribe(data => {
					this.jsonApiService.message(data.message);
					this.closeAddUserModal(modal);
					this.load();
				})
			} else {
				// 删除为null的字段
				for(let key in this.userObj){
					if(!this.userObj[key]&&this.userObj[key]!=0){
						delete this.userObj[key]
					}
				}
				this.jsonApiService.http_obj("sanitationUser/edit.html", this.userObj).subscribe(data => {
					this.jsonApiService.message(data.message);
					this.closeAddUserModal(modal);
					this.load();
				})
			}
		}
	}


	// 下发指令
	issueInstructions(row) {
		this.jsonApiService.confirm_message("确定下发指令么?").then(() => {
			let reqdata = 'id=' + row.id;
			this.jsonApiService.http("sanitationUser/issueInstructions.html", reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				this.load();
			})
		})
	}
	/**
	 * 图片的方法
	 */
	imgList: any = [];
	imgLocalList:any=[];
	isViewer:boolean = false; //默认隐藏
	isViewer1:boolean = false; //默认隐藏
	//显示图片组件
	viewer1: any='';
	imageInfo : any={
        "localImg":[],
        "imageList":[],
        "describe": '用户照片'
	}
	
	 //显示图片组件
	 viewer: any='';
	 fileList: File = null;
	
	bigImgClick(){
		// modal.show();
		if(this.isViewer && $(".viewer-container").length >0){
			System.import('assets/js/viewer/viewer.js').then(
				()=>{System.import('assets/js/viewer/bootstrap.bundle.min.js').then(
					()=>{System.import('assets/js/viewer/viewer.css').then(()=>{
						this.showImg();
					})
				})
			})
		}else{
			this.showImg();
		}
	}
	showImg(){
		var that = this;
		var imgList
		imgList = $(".imgFileList")[0];
		this.viewer = new Viewer(imgList, {
			url: 'src',
			title: function (image) {
				return image.alt + ' (' + (this.index + 1) + '/' + this.length + ')' ; 
			},
		});
		that.isViewer = true
	}
	 //上传多张
	 multifileChange(files: FileList){
		if(this.isViewer && $(".viewer-container").length >0){
			this.viewer.destroy();
		}

		var that = this;
		let multfileList = files;
		
        var reqdata = new FormData();
		reqdata.append('describe',that.imageInfo.describe);
		
		reqdata.append('businessType', '3');
		// reqdata.append('type', '1');  //type 1获取相对路径  2获取绝对路径
		reqdata.append('type', '2'); //type 1获取相对路径  2获取绝对路径

		for(var i=0;i<multfileList.length;i++){
			this.fileList = multfileList[i];
			const isJPG = this.fileList.type === 'image/jpeg'|| this.fileList.type === 'image/jpg'|| this.fileList.type === 'image/png';
			if (!isJPG) {
			this.jsonApiService.message('上传图片只能是 png, jpg, jpeg 格式!');
			return;
			}

			reqdata.append('files',multfileList[i]);
			
		}
		

		that.jsonApiService.form_http("fileUpload/upload.html",reqdata).subscribe(data=> {
			// that.jsonApiService.message(data.message);
			if(data.success){
				for(var i=0;i< data.data.length;i++){
					that.imageInfo.imageList.push(data.data[i]);
					
					let localImg;
					if(data.data[i].indexOf('http') == -1){
						if(data.data[i][0] == '/'){
							localImg = config.BaseURL + data.data[i].substr(1);
						}else{
							localImg = config.BaseURL + data.data[i];
						}
					}else{
						localImg = data.data[i];
					}
                    
					that.imageInfo.localImg.push(localImg);
					
				}

			}
		})
		

		for(let k=0;k<$(".up").length;k++){
			$(".up")[k].value=null;
		}
		
    }
	
	//删除图片
	deleteImg(index,i){
        if(index == 1){
            this.imageInfo.imageList.splice(i,1);
            this.imageInfo.localImg.splice(i,1);
        }
		if(this.isViewer && $(".viewer-container").length >0){
			this.viewer.destroy();
		}
    }
	// 关闭图片查看
	closeImgModal1(modal){
		modal.hide();
		this.imgList = [];
		this.imgLocalList = [];
	}

	// 点击Table中的查看图片
	showImg1(row,modal){
		this.imgList = [];
		this.imgLocalList = [];
		
		this.imgList = row.userPic.split(",");
		let localImg;
		for(var i=0;i< this.imgList.length;i++){

			if(this.imgList[i].indexOf('http') == -1){
				if(this.imgList[i][0] == '/'){
					localImg = config.BaseURL + this.imgList[i].substr(1);
				}else{
					localImg = config.BaseURL + this.imgList[i];
				}
			}else{
				localImg = this.imgList[i];
			}

			this.imgLocalList.push(localImg);
		}
		console.log(this.imgLocalList)
		modal.show();
		if(this.isViewer1 && $(".viewer-container").length >0){
			this.viewer1.destroy();
		}

	}
	bigimg(){
		if(this.isViewer1 && $(".viewer-container").length >0){
			System.import('assets/js/viewer/viewer.js').then(
				()=>{System.import('assets/js/viewer/bootstrap.bundle.min.js').then(
					()=>{System.import('assets/js/viewer/viewer.css').then(()=>{
						this.showBigImg();
					})
				})
			})
		}else{
			this.showBigImg();
		}
	}
	showBigImg(){
		var that = this;
		var imgList
		imgList = $(".imagesInfo1")[0];
		console.log(imgList)
		this.viewer1 = new Viewer(imgList, {
			url: 'src',
			title: function (image) {
				return image.alt + ' (' + (this.index + 1) + '/' + this.length + ')' ; 
			},
		});
		that.isViewer1 = true
	}
}